<?php

namespace Modules\Shop\Http\Controllers;

use foo\bar;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Routing\Controller;
use Modules\Shop\Entities\Category;
use Modules\Shop\Http\Requests\CategoryRequest;

class CategoryController extends Controller
{
    /**
     * Display a listing of the resource.
     * @return Response
     */
    public function index()
    {
       //获取分类表中的所有数据
       // $categorys = Category::get();
        //获取梳妆分类数据
        $categorys = Category::getTreeCategory();
        return view('shop::category.index',compact('categorys'));
    }

    /**
     * Show the form for creating a new resource.
     * @return Response
     */
    public function create()
    {
        return view('shop::create');
    }

    /**
     * Store a newly created resource in storage.
     * @param  Request $request
     * @return Response
     */
    public function store(CategoryRequest $request)
    {
        //将post数据中的值写入分类表
        Category::create($request->all());
        //设置闪存并返回
        session()->flash('success','分类添加成功');
        return back();
    }

    /**
     * Show the specified resource.
     * @return Response
     */
    public function show()
    {
        return view('shop::show');
    }

    /**
     * Show the form for editing the specified resource.
     * @return Response
     */
    public function edit($id)
    {
        //找到当前$id对应的分类数据
        $category = Category::find($id);
        //获取所有的分类数据
        $categorys = Category::getTreeCategory($category);
        return view('shop::category.edit',compact('categorys','category'));
    }

    /**
     * Update the specified resource in storage.
     * @param  Request $request
     * @return Response
     */
    public function update(CategoryRequest $request,$id)
    {
        //找到对应id的分类数据
        $category = Category::find($id);
        //获取post数据
        $post = $request->all();
        $category->cname = $post['cname'];
        $category->pid = $post['pid'];
        $category->save();
        //设置闪存并跳转
        session()->flash('success','分类编辑成功');
        return redirect()->route('category.index');

    }

    /**
     * Remove the specified resource from storage.
     * @return Response
     */
    public function destroy($id)
    {
        //删除之前应该先判断当前分类是否有子分类,如果有,提示不能直接删除
        $category = Category::find($id);
        if (Category::hasChildCategory($category)){
            //如果是真,代表有子集,应该提示不能直接删除
            session()->flash('danger','请先删除当前分类的子分类,再来删除该分类');
            return back();
        }
        //删除对应id的分类数据
        Category::destroy($id);
        //设置闪存并返回
        session()->flash('success','分类删除成功');
        return back();
    }
}
